<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span class="active">报修列表</span>
    </div>

    <el-row>
      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="关键字">
            <el-input v-model="query.key"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="地址">
            <el-input v-model="query.address"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="电话">
            <el-input v-model="query.tel"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="10">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="活动时间">
            <span class="demonstration">时间查询</span>
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="报修状态">
            <el-select v-model="query.state" clearable>
              <el-option label="全部" :value="0"></el-option>
              <el-option 
                v-for="item in repairStates" 
                :key="item.id" 
                :label="item.name" 
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="4">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="维修类型">
            <el-select v-model="query.type" clearable>
              <el-option
                v-for="item in repairTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="居民">
            <el-input v-model="query.userid" placeholder="请输入居民ID"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" style="margin-left: 20px">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </el-row>
    <!-- 表格 -->
    <BaseTable
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading="loading"
      :isShowSelection="true"
      @selection-change="handleSelectionChange"
      @edit="handleClick"
      @delete="handleDelete"
      @status-click="handleStatusClick"
    >
      <template #options="{row}">
        <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </BaseTable>
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="query.psize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
    >
    </el-pagination>

    <!-- 状态修改弹窗 -->
    <el-dialog title="修改维修状态" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="当前状态">
          <el-select v-model="editForm.state" placeholder="请选择状态">
            <el-option 
              v-for="item in repairStates"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleStatusUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
import { list, del, add, typeList, stateList } from '../api/repairs'
import BaseTable from './BaseTable.vue'
export default {
  name: 'RepairsView',
  components: {
    BaseTable,
  },
  data() {
    return {
      loading: true,
      tableColumn: [
        {
          prop: 'id',
          label: 'ID',
        },
        {
          prop: 'typename',
          label: '故障类型',
        },
        {
          prop: 'address',
          label: '维修地址',
        },
        {
          prop: 'images',
          label: '故障图片',
          slotname: 'images'
        },
        {
          prop: 'content',
          label: '故障描述',
        },
        {
          prop: 'username',
          label: '业主名称',
        },
        {
          prop: 'addtime',
          label: '维修日期',
        },
        {
          prop: 'statename',
          label: '状态',
          slotname: 'status'
        },
        {
          prop: 'options',
          label: '操作',
          slotname: 'options',
        },
      ],
      form: {
        name: '',
        region: '',
      },
      query: {
        page: 1,
        psize: 10,
        key: '',
        address: '',
        tel: '',
        begindate: '',
        enddate: '',
        state: '',
        type: '',
        userid: ''
      },
      dateRange: '',

      tableData: [],
      counts: 0,
      multipleSelection: [],
      repairTypes: [],
      repairStates: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      // 状态修改弹窗相关
      dialogVisible: false,
      editForm: {
        id: 0,
        state: 1
      }
    }
  },
  created() {
    this.getList()
    this.getRepairTypes()
    this.getRepairStates()
  },

  methods: {
    async getList() {
      this.loading = true
      try {
        let {
          data: { counts, list: listData },
        } = await list(this.query)
        this.counts = counts
        this.tableData = listData
        this.loading = false
        console.log('获取到的数据:', listData)
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    async getRepairTypes() {
      try {
        const { data: { list: typeListData } } = await typeList()
        this.repairTypes = typeListData
      } catch (error) {
        console.error('获取维修类型失败:', error)
      }
    },
    async getRepairStates() {
      try {
        const { data: { list: stateListData } } = await stateList()
        this.repairStates = stateListData
      } catch (error) {
        console.error('获取维修状态失败:', error)
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await del({ id: row.id })
        await this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        } else {
          console.error('删除失败:', error)
        }
      }
    },
    handleClick(row) {
      console.log('编辑操作:', row)
      // 这里可以添加编辑逻辑
    },
    // 点击状态显示弹窗
    handleStatusClick(row) {
      this.editForm.id = row.id
      this.editForm.state = row.state
      this.dialogVisible = true
    },
    // 更新状态
    async handleStatusUpdate() {
      try {
        await add({
          id: this.editForm.id,
          state: this.editForm.state
        })
        this.dialogVisible = false
        await this.getList()
        this.$message.success('状态更新成功')
      } catch (error) {
        console.error('状态更新失败:', error)
        this.$message.error('状态更新失败')
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.query.psize = val;
      this.query.page = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.query.page = val;
      this.getList();
    },
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.query.begindate = val[0]
        this.query.enddate = val[1]
      } else {
        this.query.begindate = ''
        this.query.enddate = ''
      }
    },
    handleSearch() {
      this.query.page = 1
      this.getList()
    },
    handleReset() {
      this.query = {
        page: 1,
        psize: 10,
        key: '',
        address: '',
        tel: '',
        begindate: '',
        enddate: '',
        state: '',
        type: '',
        userid: ''
      }
      this.dateRange = ''
      this.getList()
    },
    async handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择要删除的记录')
        return
      }
      
      try {
        await this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 条记录吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        
        // 批量删除接口需要后端支持
        // const ids = this.multipleSelection.map(item => item.id)
        // 这里需要添加批量删除的API调用
        this.$message.info('批量删除功能待实现')
        
        await this.getList()
        this.$message.success('批量删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    }
  },
}
</script>
<style lang="less" scoped>
@import '../assets/css/repairs.less';
</style>
